package com.cqupt.slewing


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.cqupt.slewing.room.Item
import com.cqupt.slewing.room.ItemViewModel
import com.daimajia.swipe.SwipeLayout
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


class MyAdapter(val context: FragmentActivity) :
    RecyclerSwipeAdapter<MyAdapter.MyViewHolder>() {
    private val myViewModel: MyViewModel = ViewModelProvider(context)[MyViewModel::class.java]
    private val itemViewModel: ItemViewModel = ViewModelProvider(context)[ItemViewModel::class.java]
    private var allItems: List<Item> = ArrayList<Item>()

    fun setAllItems(allItems: List<Item>) {
        this.allItems = allItems
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.cell_history, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val item: Item = allItems[position]

        holder.macID.text = item.macID
        holder.status.text = item.status

        holder.surface.setOnClickListener {
            val bundle = bundleOf("macID" to item.macID)
            val controller = Navigation.findNavController(it)
            controller.navigate(R.id.action_favoritesFragment_to_trackFragment, bundle)
        }
        holder.bottom.setOnClickListener {
            GlobalScope.launch(Dispatchers.IO) {
                itemViewModel.removeItem(item)
                myViewModel.popDevice(item.macID)
                myViewModel
            }
            Toast.makeText(context, "delete successfully", Toast.LENGTH_SHORT).show()
        }
    }

    override fun getItemCount(): Int {
        return allItems.size
    }

    override fun getSwipeLayoutResourceId(position: Int): Int {
        return position
    }


    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val swipeLayout: SwipeLayout = itemView.findViewById(R.id.swipe_layout)
        val surface: ConstraintLayout = itemView.findViewById(R.id.surface_view)
        val bottom: ConstraintLayout = itemView.findViewById(R.id.bottom_wrapper)
        val macID: TextView = itemView.findViewById(R.id.textViewMac)
        val status: TextView = itemView.findViewById(R.id.textViewName)
    }
}
